package com.example.ywj.toutiao;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.ywj.toutiao.bean.Set;
import com.example.ywj.toutiao.bean.User;
import com.example.ywj.toutiao.compoents.MyGlideEngine;
import com.example.ywj.toutiao.utils.Constant;
import com.example.ywj.toutiao.utils.ImageUtil;
import com.example.ywj.toutiao.utils.ResponseApi;
import com.example.ywj.toutiao.utils.SetAdapter1;
import com.example.ywj.toutiao.utils.SetAdapter2;
import com.example.ywj.toutiao.utils.SpUtils;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.hb.dialog.myDialog.MyAlertDialog;
import com.hb.dialog.myDialog.MyAlertInputDialog;
import com.lljjcoder.Interface.OnCityItemClickListener;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.style.cityjd.JDCityPicker;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import butterknife.BindView;
import butterknife.ButterKnife;
import es.dmoral.toasty.Toasty;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import java.util.Calendar;
import android.app.FragmentManager;


public class EditActivity extends AppCompatActivity implements View.OnClickListener,DatePickerDialog.OnDateSetListener {
    private static final String TAG = "EditActivity";

    @Override
    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
        int realMonth = monthOfYear+1;
        String newBirthday = year+"-"+realMonth+"-"+dayOfMonth;
        Set set = new Set("用户",newBirthday);
        list2.set(3,set);
        setAdapter2.notifyDataSetChanged();
        saveBirthday(newBirthday);
    }
    public void saveBirthday(String birthday){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.saveBirthday(birthday,username);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try {
                    json = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, "onResponse: "+json);
                JsonObject obj = (JsonObject) new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code ==200 && obj.has("data")){
                    Toasty.success(EditActivity.this,"修改成功",Toasty.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: "+t);
            }
        });
    }
    public String baseUrl = Constant.BASEURL;
    @BindView(R.id.edit_back)
    public TextView edit_back;
    @BindView(R.id.edit_listView1)
    public ListView edit_listView1;
    @BindView(R.id.edit_listView2)
    public ListView edit_listView2;
    public List<User> list = new ArrayList<>();
    private String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE};
    public List<Uri> pathList = new ArrayList<>();
    public ImageView iv;
    public  TextView tv_nickname;
    public SetAdapter1 setAdapter1;
    public SetAdapter2 setAdapter2;
    public  List<Set> list1;
    public  List<Set> list2;
    String username;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit);
        username = SpUtils.getString(EditActivity.this,"username");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//因为不是所有的系统都可以设置颜色的，在4.4以下就不可以。。有的说4.1，所以在设置的时候要检查一下系统版本是否是4.1以上
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(R.color.trgray));
        }
        ButterKnife.bind(this);
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            int flag1 = ContextCompat.checkSelfPermission(this,permissions[0]);
            int flag2 = ContextCompat.checkSelfPermission(this,permissions[1]);
            if(flag1!=PackageManager.PERMISSION_GRANTED||flag2!=PackageManager.PERMISSION_GRANTED){
                showDialogTipUserRequestPermission();
            }
        }
        initView();
        String username = SpUtils.getString(EditActivity.this,"username");
        getData(username);
    }
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
                    edit_listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            switch (position){
                                case 0:
                                    addImage();
                                    iv = view.findViewById(R.id.edit_item1_avatar);

                                    //Toasty.info(EditActivity.this,"123",Toasty.LENGTH_LONG).show();
                            }

                        }
                    });
                    edit_listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            switch (position){
                                case 0:
                                    tv_nickname = view.findViewById(R.id.edit_item2_value);
                                    setNickName();
                                    break;
                                case 1:
                                    setDesc();
                                    break;
                                case 2:
                                    setSex();
                                    break;
                                case 3:
                                    setBirthday();
                                    break;
                                case 4:
                                    setPlace();
                                    break;
                            }
                        }
                    });
            }
        }
    };
    public void setNickName(){
        final MyAlertInputDialog myAlertInputDialog = new MyAlertInputDialog(this).builder()
                .setTitle("请输入")
                .setEditText("");
        myAlertInputDialog.setPositiveButton("确认", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Set set = new Set("用户",myAlertInputDialog.getResult());
                list2.set(0,set);
                setAdapter2.notifyDataSetChanged();
                saveNickName(myAlertInputDialog.getResult());
                myAlertInputDialog.dismiss();
            }
        }).setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //showMsg("取消");
                myAlertInputDialog.dismiss();
            }
        });
        myAlertInputDialog.show();
    }
    public void saveNickName(String nickname){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.saveNickName(nickname,username);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try {
                    json = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, "onResponse: "+json);
                JsonObject obj = (JsonObject) new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code ==200 && obj.has("data")){
                    Toasty.success(EditActivity.this,"修改成功",Toasty.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: "+t);
            }
        });
    }
    public void setSex(){
        AlertDialog.Builder builder = new AlertDialog.Builder(EditActivity.this);
        //    指定下拉列表的显示数据
        final String[] sex = {"男","女"};
        //    设置一个下拉的列表选择项
        builder.setTitle("请选择性别");
        builder.setSingleChoiceItems(sex,-1, new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                Set set;
                if(which == 0){
                    set = new Set("介绍",sex[0]);
                    list2.set(2,set);
                    setAdapter2.notifyDataSetChanged();
                    saveSex(sex[0]);
                }else if(which == 1){
                    set = new Set("介绍",sex[1]);
                    list2.set(2,set);
                    setAdapter2.notifyDataSetChanged();
                    saveSex(sex[1]);
                }
            }
        });
        builder.show();
    }
    public void saveSex(String sex){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.saveSex(sex,username);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try {
                    json = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, "onResponse: "+json);
                JsonObject obj = (JsonObject) new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code ==200 && obj.has("data")){
                    Toasty.success(EditActivity.this,"修改成功",Toasty.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: "+t);
            }
        });
    }
    public void setBirthday(){
        Calendar now = Calendar.getInstance();
        DatePickerDialog dpd = DatePickerDialog.newInstance(
                EditActivity.this,
                now.get(Calendar.YEAR), // Initial year selection
                now.get(Calendar.MONTH), // Initial month selection
                now.get(Calendar.DAY_OF_MONTH) // Inital day selection
        );
        dpd.show(getSupportFragmentManager(), "Datepickerdialog");
    }
    public void setDesc(){
        final MyAlertInputDialog myAlertInputDialog = new MyAlertInputDialog(this).builder()
                .setTitle("请输入")
                .setEditText("");
        myAlertInputDialog.setPositiveButton("确认", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Set set = new Set("介绍",myAlertInputDialog.getResult());
                list2.set(1,set);
                setAdapter2.notifyDataSetChanged();
                saveDesc(myAlertInputDialog.getResult());
                myAlertInputDialog.dismiss();
            }
        }).setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myAlertInputDialog.dismiss();
            }
        });
        myAlertInputDialog.show();
    }
    public void saveDesc(String desc){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.saveDesc(desc,username);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try {
                    json = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, "onResponse: "+json);
                JsonObject obj = (JsonObject) new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code ==200 && obj.has("data")){
                    Toasty.success(EditActivity.this,"修改成功",Toasty.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: "+t);
            }
        });
    }
    public void setPlace(){
        JDCityPicker cityPicker = new JDCityPicker();
        cityPicker.init(this);
        cityPicker.setOnCityItemClickListener(new OnCityItemClickListener() {
            @Override
            public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
                String newPlace = province+""+city+""+district;
                Set set = new Set("地区",newPlace);
                list2.set(4,set);
                setAdapter2.notifyDataSetChanged();
                savePlace(newPlace);
                Log.i(TAG, "onSelected: "+province+"-"+city+"-"+district);
            }
            @Override
            public void onCancel() {
            }
        });
        cityPicker.showCityPicker();
    }
    public void savePlace(String place){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.savePlace(place,username);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try {
                    json = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, "onResponse: "+json);
                JsonObject obj = (JsonObject) new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code ==200 && obj.has("data")){
                    Toasty.success(EditActivity.this,"修改成功",Toasty.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: "+t);
            }
        });
    }
    public void initView(){
        Typeface font = Typeface.createFromAsset(getAssets(), "iconfont.ttf");
        edit_back.setTypeface(font);
        edit_back.setText(getResources().getString(R.string.back));
        edit_back.setOnClickListener(this);
    }
    public void getData(String username){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.getInfoByUsername(username);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try{
                    json = response.body().string();
                    Log.i(TAG, "onResponse: "+json);
                }catch (Exception e){
                    e.printStackTrace();
                }
                JsonObject obj = (JsonObject)new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code == 200 && obj.has("data")){
                    JsonArray objArr = obj.getAsJsonArray("data");
                    Gson gson = new Gson();
                    list = gson.fromJson(objArr,new TypeToken<ArrayList<User>>(){}.getType());
                    list1 = new ArrayList<>();
                    list2 = new ArrayList<>();
                    String key1[] = {"头像"};
                    String key2[] = {"用户名","介绍","性别","生日","地区"};
                    String value[] = new String[5];
                    //String value2[] = {};
                    //value2[0] = list.get(0).getAvatar();
                    value[0] = list.get(0).getNickname();
                    value[1] = list.get(0).getDesc();
                    value[2] = list.get(0).getSex();
                    value[3] = list.get(0).getBirthday();
                    value[4] = list.get(0).getPlace();
                    list1.add(new Set(key1[0],list.get(0).getAvatar()));
                    for(int j = 0 ;j<key2.length;j++){
                        list2.add(new Set(key2[j],value[j]));
                    }
                    setAdapter1 = new SetAdapter1(list1);
                    edit_listView1.setAdapter(setAdapter1);
                    setAdapter2 = new SetAdapter2(list2);
                    edit_listView2.setAdapter(setAdapter2);
                    Message msg = Message.obtain();
                    msg.what = 0;
                    handler.sendMessage(msg);
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: 请求失败");
            }
        });
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.edit_back:
                finish();
                break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 200 && resultCode == RESULT_OK) {
            pathList = Matisse.obtainResult(data);
            iv.setImageURI(pathList.get(0));
            updateAvatar(pathList.get(0));
        }
    }
    public void updateAvatar(Uri uri){
        File file = new File(ImageUtil.getRealFilePath(EditActivity.this,uri));
        RequestBody requestFile =
                RequestBody.create(MediaType.parse("image/png"), file);
        MultipartBody.Part body =
                MultipartBody.Part.createFormData("actimg", file.getName(), requestFile);
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constant.BASEURL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        ResponseApi responseInfoApi = retrofit.create(ResponseApi.class);
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("text/plain"),username);
        Call<ResponseBody> call  = responseInfoApi.updateAvatar(body,requestBody1);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try {
                    json = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, "onResponse: "+json);
                JsonObject obj = (JsonObject) new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code ==200 && obj.has("data")){
                    Toasty.success(EditActivity.this,"修改成功",Toasty.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: "+t);
            }
        });
    }
    public void addImage(){
        Matisse
                .from(EditActivity.this)
                //选择视频和图片
                .choose(MimeType.ofAll())
                //这两行要连用 是否在选择图片中展示照相 和适配安卓7.0 FileProvider
                .capture(true)
                .captureStrategy(new CaptureStrategy(true,"PhotoPicker"))
                //有序选择图片 123456...
                .countable(true)
                //最大选择数量为9
                .maxSelectable(1)
                //选择方向
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                //界面中缩略图的质量
                .thumbnailScale(0.8f)
                //蓝色主题
                .theme(R.style.Matisse_Zhihu)
                //Glide加载方式
                .imageEngine(new MyGlideEngine())
                //请求码
                .forResult(200);
    }
    public void showDialogTipUserRequestPermission(){
        MyAlertDialog myAlertDialog = new MyAlertDialog(this).builder()
                .setTitle("存储权限")
                .setMsg("是否开启权限")
                .setPositiveButton("确认", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startRequestPermission();
                    }
                }).setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
        myAlertDialog.show();
    }
    private void startRequestPermission() {
        ActivityCompat.requestPermissions(this, permissions, 321);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 321) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //Log.i(TAG, "onRequestPermissionsResult: "+grantResults[0]);
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    finish();
                } else {
                    //Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                    Toasty.success(this,"权限获取成功",Toasty.LENGTH_LONG).show();
                }
            }
        }
    }
}
